package com.augurit.gzcgwsp.jzfqwczz.web;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;
import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.system.web.org.form.OmUserForm;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.jzfqwczz.entity.YwYnJzfqwczcJbxx;
import com.augurit.gzcgwsp.jzfqwczz.service.IYwYnJzfqwczcJbxxService;
import com.augurit.gzcgwsp.jzfqwczz.web.form.YwYnJzfqwczcJbxxForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.rqqyjyxk.web.form.YwRqQyjyxkForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.service.IYwComQyxxService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComQyxxForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;

@SuppressWarnings("serial")
@Results({
	@Result(name ="printViewZs", location ="/gzcgwsp/jzfqwczz/YwYnJzfqwczcJbxx/preViewXkz.jsp"),
	@Result(name ="gzViewXkz", location ="/gzcgwsp/jzfqwczz/YwYnJzfqwczcJbxx/gzViewXkz.jsp"),
	@Result(name = CrudActionSupport.RELOAD, location = "yw-yn-jzfqwczc-jbxx.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczcJbxx/YwYnJzfqwczcJbxx.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczcJbxx/YwYnJzfqwczcJbxx-input.jsp"),
	@Result(name ="selectuser", location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczcJbxx/selectUser.jsp"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
	@Result(name = "printxkzs", location = "/gzcgwsp/wfex/client/wf-printExcelEx.jsp"),
    @Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/make-document.jsp"),
    @Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP)
})
public class YwYnJzfqwczcJbxxAction extends WfBusClientAction<YwYnJzfqwczcJbxxForm>{

    @Autowired
    private IWfServiceEX wfServiceEX;
	@Autowired
	private IYwYnJzfqwczcJbxxService ywYnJzfqwczcJbxxService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
    @Autowired
    private IYwPrintDocService ywPrintDocService;
    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private IYwComQyxxService qyxxService;
    @Autowired
    private ISysCodeService syscodeService;
    @Autowired
    private IOaDocCodeServiceEX oaDocCodeServiceEX;
	@Autowired
	private IWfService wfService;
	
	private YwYnJzfqwczcJbxxForm form;
    @Autowired
    private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
    
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
	private Long id;
	private Long[] checkedIds;
	private Page<YwYnJzfqwczcJbxxForm> page = new Page<YwYnJzfqwczcJbxxForm>(10);

    /**
     * 保存业务并关联流程实例
     */
    public String wfBusSave() {
    	try{
        if (form.getQyid() == null) {
            YwComQyxxForm qyxxForm = qyxxService.getFormBySqdw(form.getSqdw(),form.getTemplateCode());
            if (qyxxForm != null) {
                WfUtils.renderWfFailtureJson("该企业名称已经存在，请点击选择企业从企业列表中选择该企业！");
                return null;
            }
        }        
        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywYnJzfqwczcJbxxService, form, YwYnJzfqwczcJbxx.class.getSimpleName());
        form.setDfsj(null);
        
        if (form.getDfsj() == null) {
            String durationExpression = wfServiceEX.getProcDueExpressIonByTaskInstDbid(task.getTaskInstDbid());
            Date dfsj = wfServiceEX.calculateDueDate(form.getSarq(), durationExpression);
            form.setDfsj(dfsj);
            this.save();
        }
        String isYsl = super.getParameter("isYsl");
        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
            String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
            ywYnJzfqwczcJbxxService.changeYslState(form.getId(), 2l,null);
        }        
        
        //答复时间
        if(id!=null && StringUtils.isNotBlank(this.getTemplateCode())){
    		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
    		form.setDfsj(date);
    	}
        
        WfUtils.renderWfBusSaveJson(task, form);
	}catch (Exception e) {
  		WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
		}
        return null;
    }
    
    public String wfBusYslTuih() throws Exception {
    	try {
    		ywYnJzfqwczcJbxxService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    /**
     * 出证
     */
    public String printcz() throws Exception {
    	String taskId=getRequest().getParameter("taskInstDbid");
    	String activName="";
		if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
    	if(form.getId() != null && form.getId() > 0){
    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
    			return WfConstant.PRINT_DIR;
    		}
    	}
    
        return WfUtilsEX.wfBusPrint(form,form.getId(),activName);
    }
    
    /**
     * 保存许可证
     * @return
     */
    public String saveXkz() throws Exception{
    	//只需要保存证书的有效日期
    	String starttime=form.getStartYear()+"-"+form.getStartMonth()+"-"+form.getStartDay();
    	Date enddate=null;
    	Date startdate=null;
    	if(StringUtils.isNotBlank(form.getEndYear()) && StringUtils.isNotBlank(form.getEndMonth())
    			&& StringUtils.isNotBlank(form.getEndDay())){
    		String endtime=form.getEndYear()+"-"+form.getEndMonth()+"-"+form.getEndDay();
    		enddate=DateUtilsEX.dateFormate(endtime, "yyyy-MM-dd");
    	}
    	if(StringUtils.isNotBlank(form.getStartYear()) && StringUtils.isNotBlank(form.getStartMonth())
    			&& StringUtils.isNotBlank(form.getStartDay())){
    		String endtime=form.getStartYear()+"-"+form.getStartMonth()+"-"+form.getStartDay();
    		startdate=DateUtilsEX.dateFormate(starttime, "yyyy-MM-dd");
    	}
    	try {
			ywYnJzfqwczcJbxxService.updateXkz(form,startdate,enddate);
			getResponse().getWriter().print("success");
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 打印
     * @return
     * @throws Exception
     */
    public String printXkz() throws Exception{
    	 String tempPath="Templates/printTemplate/yncz/xkz.xls";
         logger.info("打印处置证的文件路径"+tempPath);
         String context=getRequest().getSession().getServletContext().getRealPath("");
         String inpath=context+File.separator+tempPath;
         tempPath=ywYnJzfqwczcJbxxService.writeXkzData(form,context,inpath);
         getRequest().setAttribute("templateFilePath",tempPath);
         logger.info("返回设施一览表文件路径"+tempPath);
    	return "printxkzs";
    }
    
    /**
     * 制文
     * @return
     * @throws Exception
     */
    public String makeDocument() throws Exception {
        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
            form.setRedHeadFilePath(redHeadFilePath);
        }
        
        String templateCode = getTemplateCode();
        if(templateCode != null && templateCode.trim().length() > 0){
            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
            form.setTemplatePath(printTemplatePath);
            logger.info("制文打印模版文件printTemplatePath------>"+printTemplatePath);
            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = (WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
            logger.info("制文模版文件路径------>"+printTemplatePath);
            form.setZhengwenPath(zhengwenPath);
            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
            form.setCbyw("建筑物废弃物处置证审批");
            form.setCbyw2("建筑物废弃物处置证审批");
            form.setCbyw3("建筑物废弃物处置证审批");
            form.setCbyw4("建筑物废弃物处置证审批");
            //---获取受理通知书时间---韩修改
            YwRqQyjyxkForm sltjsForm=new YwRqQyjyxkForm();
            sltjsForm.setFileCode("sltzs");
            List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(),sltjsForm.getFileCode(), form.getId());
            if(ywPrintDocFormList!=null&&ywPrintDocFormList.size()>0){
            	YwPrintDocForm ywPrintDocForm=ywPrintDocFormList.get(0);
            	form.setSlDate(DateUtilsEX.convertCommonDate(ywPrintDocForm.getCreatDate()));
            }
            if(form.getCurSeq()==null){
                Long seq=oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId());
    	        if(seq.intValue()<10){
	        	  form.setCurSeq("0"+String.valueOf(seq));
		        }else{
		        	  form.setCurSeq(String.valueOf(seq));
		        }
	                
            }
//            Long seq=oaDocCodeServiceEX.getCurSeqAndAddSeq(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId(),false);
//	        if(seq.intValue()<10){
//	        	  form.setCurSeq("0"+String.valueOf(seq));
//	        }else{
//	        	  form.setCurSeq(String.valueOf(seq));
//	        }
            WfUtilsEX.wfBusPrint(form);
            getRequest().setAttribute("isunified", false);//是否全委统一
            BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
            BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
            BaseAction.getRequest().setAttribute("entityId", form.getId());
            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
        }
        return WfConstant.MAKE_DOCUMENT; 
       }
	@Override
	public String list() throws Exception {
		ywYnJzfqwczcJbxxService.search(page, form);
		return SUCCESS;
	}
	
	/**
	 * 打印查看许可证书
	 * @return
	 */
	public String preViewXkz(){
	  	String taskId=getRequest().getParameter("taskId");
	  	//获取当前时间
	  	if(StringUtils.isBlank(form.getStartYear())){
	  		form.setStartYear(DateUtilsEX.getCurYear());
	  		form.setStartMonth(DateUtilsEX.getCurMonth());
	  		form.setStartDay(DateUtilsEX.getCurDay());
	  	}
		if(StringUtils.isNotBlank(taskId)){
			  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
				String activName=instance.getActivityName();
				String templateCode=instance.getTemplateCode();
				getRequest().setAttribute("templateCode", templateCode);
			    getRequest().setAttribute("hjmc", activName);
			
				
		}
		//if("dzgz".equals(activName)){
			String tempPath="Templates/printTemplate/yncz/xkz.xls";
	        String context=getRequest().getSession().getServletContext().getRealPath("");
	        String inpath=context+File.separator+tempPath;
	        tempPath=ywYnJzfqwczcJbxxService.writeXkzData(form,context,inpath);
	        getRequest().setAttribute("templateFilePath",tempPath);
			
		//}
	
	    return "printViewZs";
	}
	
	
	/**
	 * 打印查看许可证书
	 * @return
	 */
	public String gzViewXkz(){
	  	String taskId=getRequest().getParameter("taskId");
	  	//获取当前时间
	  	if(StringUtils.isBlank(form.getStartYear())){
	  		form.setStartYear(DateUtilsEX.getCurYear());
	  		form.setStartMonth(DateUtilsEX.getCurMonth());
	  		form.setStartDay(DateUtilsEX.getCurDay());
	  	}
		if(StringUtils.isNotBlank(taskId)){
			  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
				String activName=instance.getActivityName();
				String templateCode=instance.getTemplateCode();
				getRequest().setAttribute("templateCode", templateCode);
			    getRequest().setAttribute("hjmc", activName);
		}
		String tempPath="Templates/printTemplate/yncz/xkz.xls";
        String context=getRequest().getSession().getServletContext().getRealPath("");
        String inpath=context+File.separator+tempPath;
        tempPath=ywYnJzfqwczcJbxxService.writeXkzData(form,context,inpath);
        getRequest().setAttribute("templateFilePath",tempPath);
	    return "gzViewXkz";
	}
	
	
	@Override
    public String input() throws Exception {
		initWfOpinions();
		Long taskid=this.getTaskInstDbid();
        if(this.getTaskInstDbid()!=null){//如果还是窗口环节就不保存检查人
        	getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        }
        List<SysCodeForm> docTypeList = syscodeService.getItems("YW_QY_ZZDJ");
        getRequest().setAttribute("qyzzdj", docTypeList);
        
        return INPUT;
    }

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywYnJzfqwczcJbxxService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywYnJzfqwczcJbxxService.delete(id);
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywYnJzfqwczcJbxxService.delete(checkedIds);
		return RELOAD;
	}
	
	/**
	 * 到人员选择页面
	 * @return
	 * @throws Exception
	 */
	public String toSelectUser() throws Exception{
		String temlateCode=getParameter("temlateCode");
		List<OmUserForm> users=ywYnJzfqwczcJbxxService.getUsers(getLoginUser(),temlateCode);
		getRequest().setAttribute("users",users);
		return "selectuser";
	}
	   @Override
	    protected void prepareModel() throws Exception {
	        if(id != null){
	            form = ywYnJzfqwczcJbxxService.get(id);
	        }
	        else
	            form = new YwYnJzfqwczcJbxxForm();
	        
	        if (StringUtils.isBlank(form.getAcceptNo())) {
	        	String rq = DateUtilsEX.getYearAndMonthAndDay();
	        	form.setAcceptNo("gz26"+rq+"XXXXX");
	        }

	        if (StringUtils.isBlank(form.getSjr())) {
	            form.setSjr(this.getLoginUser().getUser().getUserName());
	        }
	        
	        if (StringUtils.isBlank(form.getCbyw())) {
	            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
	            if (wfBusTemplateForm != null) {
	                form.setCbyw(wfBusTemplateForm.getTemplateName());
	            }
	        }

	        if (StringUtils.isBlank(form.getCbbm())) {
	            form.setCbbm("余泥处");
	        }

            if (form.getSarq() == null) {
                form.setSarq(new Date());
            }
            if (form.getSqDate() == null) {
                form.setSqDate(new Date());
            }
            if (form.getCpsj() == null) {
                form.setCpsj(new Date());
            }
            if (form.getLarq() == null) {
                form.setLarq(new Date());
            }
          //答复时间
        	if(id!=null){
        		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
        		form.setDfsj(date);
        	}
            form.setSqsx("新增");
            
            LoginUserForm uform=(LoginUserForm)this.getRequest().getSession().getAttribute("SES_LOGIN_USER");
    		String username=uform.getUser().getUserName();
            //获取延期天数
        	int yqtsInt = wfServiceEX.getYqtsByProcInstId(super.getProcInstId());
        	form.setYqts(String.valueOf(yqtsInt));
        	//补交告知原因
        	if(form.getBjgzyy()==null){
        		form.setBjgzyy(this.getOpinion("jbrsl"));
        	}
        	//补交告知时间
        	if(form.getBjgzsj()==null){
        		form.setBjgzsj(new Date());
        	}
//        	//受理告知时间
//        	if(form.getBjslsj()==null){
//        		form.setBjslsj(new Date());
//        	}
        	//补交告知发出人
        	if(form.getBjgzfcr()==null){
        		form.setBjgzfcr(username);
        	}
            //补交告知受理人
        	if(form.getSldwcbrxm()==null){
        		form.setSldwcbrxm(username);
        		
        	}
        	//补交告知受理地点
        	if(form.getBjsljtdd()==null){
        		form.setBjsljtdd("广州市城市管理委员会");
        	}
	    }
	/**
	 * ׼��ҳ��ģ��
	 */

	public YwYnJzfqwczcJbxxForm getModel() {
		return form;
	}
	
	// ����getter��setter����
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwYnJzfqwczcJbxxForm> getPage() {
		return page;
	}


	public void setPage(Page<YwYnJzfqwczcJbxxForm> page) {
		this.page = page;
	}
}
